<template>
  <el-cascader
    v-model="innerValue"
    :options="groupOptions"
    :show-all-levels="false"
    clearable
    placeholder="请选择课程类型"
    @change="handleChange"
  ></el-cascader>
</template>

<script>
  import { getCourseTypeByPage } from '@/apis/courseType'

  const ENU_COURSE_TYPE_CATEGORY = {
    1: '体育类',
    2: '棋类',
    3: '文艺类',
    4: '书画类',
    99: '其他',
  }

  export default {
    props: {
      value: {
        type: [String, Number],
        default: null,
      },
    },
    data() {
      return {
        innerValue: null,
        groupOptions: [],
        list: [],
      }
    },
    watch: {
      value(val) {
        const item = this.list.find((d) => d.id === val)
        this.innerValue = item ? [item.classtype, item.id] : []
      },
    },
    async created() {
      const { list } = await getCourseTypeByPage()
      if (list && list.length > 0) {
        this.list = list

        list.forEach((item) => {
          if (item.className) {
            const group = this.getGroupByCategory(item.classtype)

            if (group) {
              group.children.push({
                label: item.className,
                value: item.id,
              })
            } else {
              this.groupOptions.push({
                label: ENU_COURSE_TYPE_CATEGORY[item.classtype] || '未知',
                value: item.classtype,
                children: [
                  {
                    label: item.className,
                    value: item.id,
                  },
                ],
              })
            }
          }
        })

        const item = list.find((d) => d.id === this.value)
        this.innerValue = item ? [item.classtype, item.id] : []
      }
    },

    methods: {
      getGroupByCategory(category) {
        return this.groupOptions.find((d) => d.value === category)
      },
      handleChange() {
        if (this.innerValue) {
          this.$emit('input', this.innerValue[1])
        } else {
          this.$emit('input', null)
        }
      },
    },
  }
</script>
